package com.youmu.sichuansfc.dao.impl;

import com.youmu.sichuansfc.dao.AreaDao;
import com.youmu.sichuansfc.domain.pojo.AreaPojo;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WYZ
 * @create 2018-02-26 14:49
 * @desc
 **/
@Repository
public class AreaDaoImpl implements AreaDao{

    private EntityManager em;
    @PersistenceContext
    public void setEm(EntityManager em) {
        this.em = em;
    }

    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public List<AreaPojo> findByParantId(Long parentId) {

        Map<String, Object> params = new HashMap<>();
        String sql  = "select * from youmu_area \n ";
        if (parentId != null){
            sql +=  " where parent_id =:parentId \n";
            params.put("parentId", parentId);
        }else {
            sql += " where level = 0 \n";
        }
        sql += "order by sequence DESC";

        Query query =  em.createNativeQuery(sql.toString(), AreaPojo.class);
        for(String key : params.keySet()){
            query.setParameter(key,params.get(key));
        }
        return query.getResultList();
    }

    @Override
    public List<AreaPojo> findByParantId(Object... parentIds) {
        if(parentIds != null && parentIds.length > 0) {
            String parentId = StringUtils.join( parentIds, " , ");
            logger.info(parentId);
            String sql = "select * from youmu_area  where parent_id in (:parentId) ";

         return  em.createNativeQuery(sql.toString(), AreaPojo.class)
                 .setParameter("parentId", parentId)
                 .getResultList();
        }
        return null;
    }
}
